require 'Common/define'
require 'Logic/Config'
require 'Common/functions'
require "View/CharactorUI/UIBreakStone"
--根据星级设置控制器
local STAR_FOR_TIPS_CTRL = {
    [80] = 0,
    [90] = 1,
    [100] = 2,
    [130] = 5,
    [140] = 6,
    [150] = 7,
}
--根据检索星级顺序
local TIPS_CTRL_FOR_STAR = {
    [1] = 80,
    [2] = 100,
    [3] = 130,
    [4] = 150,
}
UIWeapon = {};
HelperFunc.SetUIEnv(UIWeapon)
local this = UIWeapon;

this.hasInit = false;

this.txtTitleName = nil;
this.btnReset = nil;
this.btnSkin = nil;
this.btnRefine = nil;
this.btnInlay = nil;
this.txtLevel = nil;
this.txtNextLevel = nil;
this.imgCostIcon = nil;
this.txtCostNum = nil;
this.btnAddLv = nil;
this.weaponResetCost = 0            --专武重置花费
this.btnShop = nil; --快捷购买
this.hasAddRedDots = false;

---@type
this.objWeaponPos = nil;
this.objWeaponModel = nil;

this.weaponSkinConfig = nil;
this.weaponConfig = nil;
this.weaponAttrConfig = nil;
this.weaponLvCostConfig = nil;
this.attributeConfig = nil;
this.curHeroData = nil;
this.curWeaponData = nil;
this.allHero = nil;
this.inlayController = nil;
this.inlayItem = nil
this.lockText = nil;
this.goFunc = nil;
this.profession = nil;
this.maxCtrl = nil;
this.gameObjectName = nil
this.attrList = nil

this.levelup = nil;--升级
this.Com_WeaponLevelUp = nil;
this.Btn_BGClose = nil;
this.LevelUpController = nil;
this.List_WeaponAttribute = nil;
this.weaPonCtrl = nil
this.qualityObj = nil
this.qualityPos = nil
this.qualitys = { [1] = "UI_zhuanwu_blue", [2] = "UI_zhuanwu_violet", [3] = "UI_zhuanwu_yellow", [4] = "UI_zhuanwu_red", [5] = "UI_zhuanwu_white" }
this.qualityWraps = nil
---@type GoWrapper
this.goWrapper = nil
local nextAttribute = nil
local nextToAttribute = nil;
this._zwEffPlayTime = 2000 -- 专武界面特效持续时间（毫秒）
this._delayOpenLevelUp = 1800 --开启专武二级界面延迟时间
--专武升技能
this.desc1 = nil
this.desc2 = nil
this.decCtrl = nil
this.icon = nil
this.iconCtrl = nil
this.skillInfo = nil
this.helpbtn = nil
this.tb = nil
this.btnCloseSkill = nil
this.upSkill = nil
this.upDec = nil
this.upTip = nil
this.upCtrl = nil
this.skillLevelUpCtrl = nil
this.sourceCtrl = nil
this.mask = nil
this.canClickUp = nil
function UIWeapon.Init(data, closeFunc, isShowOneHero)
    --todo 应该小写 暂时先大写
    if attributeConfig == nil then
        attributeConfig = G.dataTable["t_attributelibrary"];
        weaponSkinConfig = G.dataTable["t_weaponshow"];
    end

    allHero = logicMgr.HeroManager.getOwnerHeroList(false);
    table.sort(allHero, logicMgr.HeroManager.sortHero);
    this.goFunc = closeFunc;
    this.isShowOneHero = isShowOneHero;
    curHeroData = logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(data), true);

    local name, package = getUIName(PanelResNames.UIWeapon);
    panelMgr:ShowUI(name, package, this.onCreate, Config.useLocalUI);
end
---@param obj GComponent
function UIWeapon.onCreate(obj)
    if not this.hasInit then
        this.hasInit = true;
        gameObjectName = obj.gameObjectName
        txtTitleName = obj:GetChild("titleName")
        btnReset = obj:GetChild("btn_Reset")
        btnSkin = obj:GetChild("skinBtn")
        btnRefine = obj:GetChild("spBtn")
        btnInlay = obj:GetChild("inlaylink")
        btnOneKeyLevelUp = obj:GetChild("quickBtn")
        inlayController = btnInlay:GetController("c1")
        lockText = btnInlay:GetChild("unlock");
        inlayItem = btnInlay:GetChild("item")
        this.fragmentEffectWrap = btnInlay:GetChild("effect_zwxq").wrapTarget
        txtLevel = obj:GetChild("lv_number")
        txtNextLevel = obj:GetChild("nextLevel")
        imgCostIcon = obj:GetChild("costIcon")
        txtCostNum = obj:GetChild("CostNum")
        btnAddLv = obj:GetChild("btn_addLv")
        --maxtip = obj:GetChild("maxtip");
        objWeaponPos = obj:GetChild("ModelPos");
        profession = obj:GetChild("profession")
        maxCtrl = obj:GetController("MaxLevel")
        attrList = obj:GetChild("listAttr")
        levelup = obj:GetController("levelup")
        aniLevelUp = obj:GetTransition("Effect_LevelUp")
        Com_WeaponLevelUp = obj:GetChild("Com_WeaponLevelUp")
        Btn_BGClose = Com_WeaponLevelUp:GetChild("Btn_BGClose")
        LevelUpController = Com_WeaponLevelUp:GetController("state")
        List_WeaponAttribute = Com_WeaponLevelUp:GetChild("List_WeaponAttribute")
        this.upSkill = Com_WeaponLevelUp:GetChild("btnSkill"):GetChild("Mask"):GetChild("Icon")
        this.upDec = Com_WeaponLevelUp:GetChild("skillDesc")
        this.upTip = Com_WeaponLevelUp:GetChild("skillTips")
        this.upCtrl = Com_WeaponLevelUp:GetChild("btnSkill"):GetController("improve")
        this.skillLevelUpCtrl = Com_WeaponLevelUp:GetController("skillLevelUp")
        this.btnJump = obj:GetChild("btnJump")
        this.btnSource = obj:GetChild("btnSource")
        this.UI_zhuanwu_front = obj:GetChild("UI_zhuanwu_front")
        this.UI_zhuanwu_back = Com_WeaponLevelUp:GetChild("UI_zhuanwu_back")
        this.effectController = this.btnSource:GetController("effect");
        this.sourceUIobj = obj:GetChild("UISourceMultiple");
        this.showSourceController = obj:GetController("showSource")
        this.updateLevelController = obj:GetController("update")
        this.updateLevelShowController = obj:GetController("Tips")
        this.weaPonCtrl = obj:GetController("Quality")
        this.qualityPos = obj:GetChild("Weapon_Grade_Front")
        this.btnShop = obj:GetChild("ShopBtn");
        this.isShowOneController = obj:GetController("isShowOne")
        this.helpbtn = obj:GetChild("help")
        this.btnCloseSkill = obj:GetChild("n112")
        this.desc1 = obj:GetChild("skillDesc")
        this.desc2 = obj:GetChild("skillDesc2")
        this.decCtrl = obj:GetController("showSkillDetial")
        this.tb = obj:GetChild("btnSkill")
        this.icon = this.tb:GetChild("Mask"):GetChild("Icon")
        this.iconCtrl = this.tb:GetController("improve")
        this.mask = obj:GetChild("mask")
        this.sourceCtrl = obj:GetController("btnSource")
        attrList.itemRenderer = this.SetData
        List_WeaponAttribute.itemRenderer = this.rendererWeaponAttributeItem
        goWrapper = GoWrapper.New()
        effWrapper = GoWrapper.New();
        effCtrl = obj:GetController("WeaponBreak");
        effCtrl.selectedIndex = 0;--这个控制器没用，
        this.addEvent();
    end
    skillInfo = dataTable.getDataTable("t_weaponskill")[150000 + tonumber(curHeroData.partnerModelId)]
    if this.isShowOneHero then
        this.isShowOneController.selectedIndex = 1;
        this.btnSource.visible = false;
    else
        this.btnSource.visible = true;
        this.isShowOneController.selectedIndex = 0;
    end
    btnInlay.text = ""
    this.firstEnter = true;
    profession.visible = false;
    this.mask.visible = false
    this.refresh();
    this.refreshShop();
    this.UpSkill()
    this.FreshIcon()
    canClickUp = true
end

function UIWeapon.addEvent()
    btnReset.onClick:Add(this.onClickReset)
    btnSkin.onClick:Add(this.onClickSkin)
    btnRefine.onClick:Add(this.onClickRefine)
    btnInlay.onClick:Add(this.onClickInlay)
    btnAddLv.onClick:Add(this.onClickAddLv)
    btnOneKeyLevelUp.onClick:Add(this.onClickOneKeyAddLv)
    this.btnJump.onClick:Add(this.onClickSource)
    this.btnSource.onClick:Add(this.onClickSource)
    Btn_BGClose.onClick:Add(this.CloseLevelPanel)
    this.btnShop.onClick:Add(this.onClickShop);
    this.helpbtn.onClick:Add(function()
        logicMgr.UIShowManager.ShowCommonTips("HelpTitle47", "HelpDes47", "FunctionStory404")
    end)
    this.tb.onClick:Add(function()
        this.decCtrl.selectedIndex = 1
    end)
    btnCloseSkill.onClick:Add(function()
        this.decCtrl.selectedIndex = 0
    end)
end

function UIWeapon.removeEvent()
    btnReset.onClick:Clear()
    btnSkin.onClick:Clear()
    btnRefine.onClick:Clear()
    btnInlay.onClick:Clear()
    btnAddLv.onClick:Clear()
    btnOneKeyLevelUp.onClick:Clear()
    this.btnJump.onClick:Clear()
    this.btnSource.onClick:Clear()
    Btn_BGClose.onClick:Clear();
    this.btnShop.onClick:Clear();
    this.helpbtn.onClick:Clear()
    this.tb.onClick:Clear()
    btnCloseSkill.onClick:Clear()
end

function UIWeapon.LocalListenEvent()
    ListenEvent(Config.EventType.Reset_Weapon, this.onWeaponChanged);
    ListenEvent(Config.EventType.Update_Weapon, this.onWeaponChanged);
    ListenEvent(Config.EventType.Update_WeaponAttrId, this.onWeaponChanged);
    ListenEvent(Config.EventType.Fragment_Wear, this.FragmentWear)
    ListenEvent(Config.EventType.Fragment_Unwear, this.FragmentUnwear)
    ListenEvent(Config.EventType.Fragment_Replace, this.FragmentSwap)
    ListenEvent(Config.EventType.Fresh_Bag, this.updateSource);
    ListenEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    ListenEvent(Config.EventType.HeroWeapon_LevelUp, this.dispatchWeaponLevelUp)
    ListenEvent(Config.EventType.UpdateUIWeapon, this.LoadPrefab)
end

function UIWeapon.LocalCloseEvent()
    CloseEvent(Config.EventType.Reset_Weapon, this.onWeaponChanged);
    CloseEvent(Config.EventType.Update_Weapon, this.onWeaponChanged);
    CloseEvent(Config.EventType.Update_WeaponAttrId, this.onWeaponChanged);
    CloseEvent(Config.EventType.Fragment_Wear, this.FragmentWear)
    CloseEvent(Config.EventType.Fragment_Unwear, this.FragmentUnwear)
    CloseEvent(Config.EventType.Fragment_Replace, this.FragmentSwap)
    CloseEvent(Config.EventType.Fresh_Bag, this.updateSource);
    CloseEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    CloseEvent(Config.EventType.HeroWeapon_LevelUp, this.dispatchWeaponLevelUp)
    CloseEvent(Config.EventType.UpdateWeaponRank, this.LoadPrefab)
    UIRedDots.removeViewEvent(PanelResNames.UIWeapon)
end

function UIWeapon.OnDestroy()
    this.hasInit = false
    this.removeEvent();
    if effWrapper then
        effWrapper:Dispose()
        effWrapper = nil
    end
    if objWeaponModel then
        destroyImmediate(objWeaponModel)
        objWeaponModel = nil
    end
    if qualityObj then
        destroyImmediate(qualityObj)
        qualityObj = nil
    end
    if this.qualityWraps then
        this.qualityWraps:Dispose()
        this.qualityWraps = nil
    end
    if this.effDrawWrapper then
        this.effDrawWrapper:Dispose()
        this.effDrawWrapper = nil
    end
    if this.effDrawWrapper1 then
        this.effDrawWrapper1:Dispose()
        this.effDrawWrapper1 = nil
    end
    if this.effDelayTimer then
        utimer.remove(this.effDelayTimer)
        this.effDelayTimer = nil
    end
    goWrapper = nil;
end

function UIWeapon.OnEnable()
    this.LocalListenEvent();
end

function UIWeapon.OnDisable()
    this.LocalCloseEvent();
    this.hasAddRedDots = false;
end

function UIWeapon.FreshIcon()
    icon.url = "ui://SkillAtlas/" .. G.dataTable["t_skillinfo"][tostring(skillInfo[20].f_WeaponSkill)].f_SkillIcon
    local index = math.floor(curWeaponData.level / 20)
    this.iconCtrl.selectedIndex = index > 3 and 3 or index
end
function UIWeapon.UpIcon()
    this.upSkill.url = "ui://SkillAtlas/" .. G.dataTable["t_skillinfo"][tostring(skillInfo[20].f_WeaponSkill)].f_SkillIcon
    this.upDec.text = getLanguage(skillInfo[tonumber(curWeaponData.level)].f_WeaponSkillDesc)
    if curWeaponData.level == 20 then
        this.upTip.text = getLanguage("WeaponSkillText3")
    else
        this.upTip.text = getLanguage("WeaponSkillText4")
    end
    this.upCtrl.selectedIndex = math.floor(curWeaponData.level / 20)
end

function UIWeapon.UpSkill()
    this.desc1.itemRenderer = this.ShowDec
    this.desc1.numItems = table.getn(skillInfo)
    this.desc2.itemRenderer = this.ShowDecTwo
    this.desc2.numItems = 1
end

function UIWeapon.ShowDec(idx, obj)
    local config = skillInfo[(idx + 1) * 20]
    local str = string.format(getLanguage("WeaponSkillText1"), config.f_WeaponLevel) .. getLanguage(config.f_WeaponSkillDesc)
    if curWeaponData.level < config.f_WeaponLevel then
        str = string.TextColor(str .. getLanguage("WeaponSkillText2"), "#B7B0B0")
    end
    obj:GetChild("DesText").text = str
end

function UIWeapon.ShowDecTwo(idx, obj)
    obj:GetChild("DesText").text = getLanguage(G.dataTable["t_skillinfo"][tostring(skillInfo[20].f_WeaponSkill)].f_Desc)
end
--- 等级升级
function UIWeapon.onWeaponChanged(msg)
    if canClickUp then
        resMgr:LoadModelPrefab("UIEff/UI_zhuanwu_01", function(prefab)
            if this.effDrawWrapper == nil then
                this.effDrawWrapper = GoWrapper.New();
            end
            if this.effObj ~= nil then
                destroyImmediate(this.effObj);
                this.effObj = nil;
            end
            this.effObj = newObject(prefab)
            this.effDrawWrapper:SetWrapTarget(this.effObj, false)
            Util.Lua_SetLocalRotationXYZ(this.effObj.transform, 0, 0, 0);
            this.UI_zhuanwu_front:SetNativeObject(this.effDrawWrapper)
        end)
    end
    utimer.timeCall(function()
        if this.effObj ~= nil then
            destroyImmediate(this.effObj);
            this.effObj = nil;
        end
        canClickUp = true
    end, this._zwEffPlayTime, 1);
    --- 装备会英雄英雄属性值，更新英雄属性
    if curHeroData then
        logicMgr.HeroManager.updateHeroBaseAttr(curHeroData.partnerId, true, nil, nil, nil, true);
    end
    this.refresh(msg);
    this.UpSkill()
    this.FreshIcon()
    FireEvent(Config.EventType.HeroWeapon_LevelUp)
end

function UIWeapon.SetData(index, obj)
    local n = maxCtrl.selectedIndex;
    local config = nextAttribute[index + 1]
    local _attrText = obj:GetChild("attrText")
    local _numText = obj:GetChild("num")
    local _upNumText = obj:GetChild("upNum")
    local Type = obj:GetController("Type")
    local icon = obj:GetChild("loader_icon")
    _numText.width = 114

    HelperFunc.SetIcon(icon, "attr" .. config[1], EnumConst.ItemShowType.ICON)
    local attrNumStr, attrName = this.SetText(config);
    local confis;
    if nextToAttribute ~= nil then
        confis = nextToAttribute[index + 1]
        local attrNumStrs = this.SetText(confis);
        _upNumText.text = attrNumStrs;
    end
    _attrText.text = attrName;
    _numText.text = attrNumStr;
    if index < 3 then
        if n == 2 then
            Type.selectedIndex = 1;
        else
            Type.selectedIndex = 0;
        end
    else
        local lv = curWeaponData.level
        Type.selectedIndex = lv < 20 and 2 or ((lv >= 20 and lv < 40) and 3 or ((lv >= 40 and lv < 60) and 4 or 1))
    end
end

function UIWeapon.SetText(config)
    local attrId = config[1];
    local tempNum = 1
    if logicMgr.HeroPotentialMgr.IsAtkHpDef(attrId) then
        tempNum = logicMgr.HeroPotentialMgr.WeaponCrease()
    end
    local attrNum = math.ceil(config[2]*tempNum);
    local attrSingle = attributeConfig[tostring(attrId)];
    local attrName = attrSingle.f_AttributeName;
    local attrNumStr = attrSingle.f_AttributeType == 1 and getNumString(attrNum) or string.format("+%0.1f%%", tostring(attrNum / 100));
    return attrNumStr, attrName;
end

function UIWeapon.refresh(msg)
    UIRedDots.addViewListen(PanelResNames.UIWeapon, gameObjectName .. btnSkin.gameObjectName, btnSkin, Config.RedDotsType.WeaponSkin, curHeroData.partnerId);
    UIRedDots.addViewListen(PanelResNames.UIWeapon, "btnOneKeyLevelUp", btnOneKeyLevelUp, Config.RedDotsType.HeroWeapon, curHeroData.partnerId);
    local configId = 150000 + tonumber(curHeroData.partnerModelId);
    weaponConfig = G.dataTable["t_weapon"][tostring(configId)];
    this.weaponResetCost = weaponConfig.f_ResetCostDiamond
    if msg then
        curWeaponData = msg;
    else
        curWeaponData = logicMgr.EquipManager.tabWeapon[tostring(curHeroData.partnerId)];
    end
    if not curWeaponData then
        curWeaponData = logicMgr.EquipManager.tabWeapon[tostring(curHeroData.partnerId)];
    end
    if curWeaponData == nil then
        printError("UIWeapon is error", curHeroData.name, curHeroData.partnerModelId, tostring(curHeroData.partnerId))
        return
    end
    local level = G.dataTable["t_global"]["53"]["f_int_value"];
    if curWeaponData.level >= 60 then
        this.sourceCtrl.selectedIndex = 1
    else
        this.sourceCtrl.selectedIndex = 0
    end
    if curWeaponData.level >= level then
        local itemId = StrangeFragmentManager.GetCurrentEquipFragment(curHeroData.partnerId)
        if itemId then
            local item = CtrlManager.GetCtrl(PanelNames.Item);
            if item ~= nil then
                item.initData(inlayItem, itemId, 1, true, nil, curHeroData.partnerId);
            end
            inlayController.selectedIndex = 0;
        else
            inlayController.selectedIndex = 2;
        end
    else
        lockText.text = string.format(getLanguage("WeaponUi_21"), level)
        inlayController.selectedIndex = 1;

    end
    if curWeaponData.attiredId == 0 then
        curWeaponData.attiredId = decodeJsonStrToTabel(weaponConfig.f_WeaponShow)[1][2];
    end

    txtTitleName.text = getLanguage(weaponConfig.f_WeaponName);
    txtLevel.text = tostring(curWeaponData.level);

    weaponAttrConfig = decodeJsonStrToTabel(weaponConfig.f_WeaponValue);
    weaponLvCostConfig = decodeJsonStrToTabel(weaponConfig.f_WeaponEnergyCost);
    --maxtip.visible = false;
    this.effectController.selectedIndex = 0;
    if curWeaponData.level < weaponConfig.f_MaxLevel then
        if this.curWeaponData.level == 0 then
            maxCtrl.selectedIndex = 0
        else
            maxCtrl.selectedIndex = 1
        end

        txtNextLevel.visible = true
        txtNextLevel.text = string.format(getLanguage("Level"), curWeaponData.level + 1) .. "激活"
        local attrIndex = curWeaponData.level + 1 --level从0开始的
        nextAttribute = weaponAttrConfig[attrIndex];
        nextToAttribute = weaponAttrConfig[attrIndex + 1];
        local lvCost = weaponLvCostConfig[attrIndex];

        attrList.numItems = #nextAttribute

        imgCostIcon.visible = true
        txtCostNum.visible = true
        local itemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(lvCost[1]);
        imgCostIcon.url = EnumConst.AtlasPath.ItemAtlas .. itemConfig.icon
        local itemNum = logicMgr.ItemManager.getCurrencyCountByModelId(lvCost[1]);
        local costNumStr = getNumString(itemNum)
        this.costId = lvCost[1]
        if itemNum >= lvCost[2] then

        else
            if not logicMgr.ItemManager.getSourceStart("UIWeapon") then
                this.effectController.selectedIndex = 1;
            end
            costNumStr = string.TextColor(costNumStr, "#FF0000");
        end
        costNumStr = costNumStr .. "/" .. getNumString(lvCost[2])
        txtCostNum.text = costNumStr
        -- this.checkUpdate()

        --btnAddLv.enabled = true
    else
        maxCtrl.selectedIndex = 2
        nextAttribute = weaponAttrConfig[weaponConfig.f_MaxLevel+1]
        attrList.numItems = #nextAttribute
    end
    this.checkUpdate()
    --奇异碎片
    local _fragmentSkillDesc = ""
    local _skillInfo, _skillDesc
    local _fragmentList = StrangeFragmentManager.GetFragmentInfoByPartnerId(curHeroData.partnerId)
    if _fragmentList then
        inlayController.selectedIndex = 0
        _skillInfo = G.dataTable["t_skill"][tostring(_fragmentList.f_SkillId)]
        if _skillInfo and _skillInfo.f_Desc then
            _skillDesc = getLanguage(_skillInfo.f_Desc)
        else
            _skillDesc = ""
        end
        _fragmentSkillDesc = _skillDesc
        this.fragmentEffectWrap:SetActive(true)
        Util.PlayAction(this.fragmentEffectWrap, "idle2", true)
    else
        this.fragmentEffectWrap:SetActive(false)
    end
    btnInlay:GetChild("text").text = _fragmentSkillDesc

    btnReset.visible = curWeaponData.level >= 1
    this.LoadPrefab()
    this.LoadPrefab()
    this.LoadPrefab()
    this.firstEnter = false;
end

function UIWeapon.LoadPrefab()
    local weaponSkin = weaponSkinConfig[tostring(curWeaponData.attiredId)];
    if weaponSkin ~= nil then
        if objWeaponModel == nil or objWeaponModel.name ~= weaponSkin.f_SpineID then
            if objWeaponModel ~= nil then
                destroy(objWeaponModel);
                objWeaponModel = nil
            end

            resMgr:LoadPrefab("Model/Weapon/" .. weaponSkin.f_SpineID, function(go)
                local m = go:GetComponent("SkeletonGraphic");
                local name;
                local Animation;
                if m then
                    m.material:SetFloat("_StencilComp", 8)
                    m.material:SetFloat("_Stencil", 1);
                end
                for i = 1, #weaponConfig.f_WeaponShow do
                    -- body
                    if curWeaponData.rank >= weaponConfig.f_WeaponShow[i][1] then
                        name = weaponSkinConfig[tostring(weaponConfig.f_WeaponShow[i][2])].f_SpineSkin;
                        Animation = weaponSkinConfig[tostring(weaponConfig.f_WeaponShow[i][2])].f_Effect;
                        m.initialSkinName = name;
                        m.startingAnimation = Animation;
                    else
                        break ;
                    end
                end
                if objWeaponModel ~= nil then
                    destroy(objWeaponModel);
                    objWeaponModel = nil
                end
                objWeaponModel = newObject(go);
                local tempPos = Vector3.New(weaponConfig.f_WeaponPos[1], weaponConfig.f_WeaponPos[2], 0);
                objWeaponModel:AddComponent(TCanvas);
                if goWrapper ~= nil then
                    goWrapper:SetWrapTarget(objWeaponModel, false)
                    objWeaponPos:SetNativeObject(goWrapper)
                    Util.Lua_SetLocalPositionXYZ(objWeaponModel.transform, tempPos.x, tempPos.y, 0);
                else
                    if objWeaponModel ~= nil then
                        destroyImmediate(objWeaponModel);
                        objWeaponModel = nil
                    end
                end
            end);
        end
    end
    this.weaPonCtrl.selectedIndex = curWeaponData.rank - 1
    local index = this.weaPonCtrl.selectedIndex
    if qualityObj ~= nil then
        destroy(qualityObj);
        qualityObj = nil
    end
    if index ~= 0 then
        local path = this.qualitys[math.ceil(index / 2)]
        if index >= 9 then
            path = this.qualitys[5]
        end
        resMgr:LoadPrefab("UIEff/" .. path, function(go)
            if qualityObj ~= nil then
                destroy(qualityObj);
                qualityObj = nil
            end
            qualityObj = newObject(go);
            if not qualityWraps then
                qualityWraps = GoWrapper.New()
            end

            qualityObj:AddComponent(TCanvas);
            qualityWraps:SetWrapTarget(qualityObj, false)
            qualityPos:SetNativeObject(qualityWraps)
            Util.Lua_SetLocalPositionXYZ(qualityObj.transform, 0, 0, 0);
        end);
    end
end

function UIWeapon.onClickReset()
    if not this.effObj then
        local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
        pop.Init("15", function(b)
            if b then
                if logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) < this.weaponResetCost then
                    UISysTips.AddMsg(getLanguage("Character_Tips7"))
                    return
                end
                canClickUp = false
                weaponHandler.sendWeaponResetMessage(curHeroData.partnerId);
            end
        end, this.weaponResetCost);
    end
end
--检查是否可以升级专武
function UIWeapon.checkUpdate()
    local configId = 150000 + tonumber(curHeroData.partnerModelId);
    local weaponConfig = G.dataTable["t_weapon"][tostring(configId)];
    --设置下级解锁控制器
    local levelStar = decodeJsonStrToTabel(weaponConfig.f_WeaponNeedStar)
    --从低级到高级
    for idx, star in ipairs(TIPS_CTRL_FOR_STAR) do
        if star > curHeroData.star then
            this.updateLevelShowController.selectedIndex = STAR_FOR_TIPS_CTRL[star];
            break ;
        end
        --突破等级超过锁定等级
    end
    if curHeroData.star >= TIPS_CTRL_FOR_STAR[#TIPS_CTRL_FOR_STAR] then
        this.updateLevelShowController.selectedIndex = 8;
    end
    if table.getn(levelStar) >= curWeaponData.level + 1 then

        local unlockStar = levelStar[curWeaponData.level + 1];
        if unlockStar <= curHeroData.star then
            --解锁
            btnAddLv.enabled = true
            updateLevelController.selectedIndex = 0
        else
            btnAddLv.enabled = false
            updateLevelController.selectedIndex = 1;
        end
    end
end

function UIWeapon.onClickSkin()
    -- 皮肤
    --[[local msg = {}
    msg.type = 1
    FireEvent(Config.EventType.Cancel_WeaponSkin, msg)
    showUI(PanelNames.UIWeaponSkin, curHeroData.partnerId);--]]
    showUI(PanelNames.UIWeaponUpgrade, curWeaponData, curHeroData)
end

function UIWeapon.onClickRefine()
    -- 淬炼
    log('onClickRefine');
end

function UIWeapon.onClickInlay()
    -- 镶嵌
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.WeaponRefine, true, btnInlay, { heroId = curHeroData.partnerId }) then
        if (not StrangeFragmentManager.GetCurrentEquipFragment(curHeroData.partnerId)) and inlayController.selectedIndex == 2 then
            local _heroInfo = HeroManager.getHeroDatabyPartnerId(this.curHeroData.partnerId, true)

            local _gemInfo = {};
            _gemInfo.part = EnumConst.EquipPartEnum.FRAGMENT
            _gemInfo.itemId = StrangeFragmentManager.GetCurrentEquipFragment(curHeroData.partnerId)
            showUI(PanelNames.UIEquipList, _heroInfo, _gemInfo)
        elseif inlayController.selectedIndex == 1 then
            --锁住 专武需达到10级才可解锁奇异碎片
            UISysTips.AddMsg(getLanguage("UIWeapon_FragmentLimit"))
        end
    end
end

function UIWeapon.LoadUpEff()
    resMgr:LoadModelPrefab("UIEff/UI_zhuanwu_02", function(prefab)
        if this.effDrawWrapper1 == nil then
            this.effDrawWrapper1 = GoWrapper.New();
        end
        if this.effFront ~= nil then
            destroyImmediate(this.effFront);
            this.effFront = nil
        end
        this.effFront = newObject(prefab)
        this.effDrawWrapper1:SetWrapTarget(this.effFront, false)
        Util.Lua_SetLocalRotationXYZ(this.effFront.transform, 0, 0, 0);
        this.UI_zhuanwu_back:SetNativeObject(this.effDrawWrapper1)
    end)
end

function UIWeapon.onClickAddLv()
    if not canClickUp then
        return
    end
    if curWeaponData.level == -1 then
        return
    end
    if curWeaponData.level >= weaponConfig.f_MaxLevel then
        --已达最大等级
        UISysTips.AddMsg(getLanguage("UIWeapon_MaxLv"))
        return ;
    end
    if this.effObj then
        utimer.remove(this.effDelayTimer)
        if levelup then
            levelup.selectedIndex = 1;
            this.mask.visible = true
            this.LoadUpEff()
            if curWeaponData.level == 20 or curWeaponData.level == 40 or curWeaponData.level == 60 then
                this.skillLevelUpCtrl.selectedIndex = 0
                this.UpIcon()
            else
                this.skillLevelUpCtrl.selectedIndex = 1
            end
        end
        if this.effObj ~= nil then
            destroyImmediate(this.effObj);
            this.effObj = nil;
        end
        return ;
    end
    local lvCost = weaponLvCostConfig[curWeaponData.level + 1];
    local itemNum = logicMgr.ItemManager.getCurrencyCountByModelId(lvCost[1]);
    if itemNum < lvCost[2] then
        this.onClickSource()
        AudioManager.Play(2010)
        return ;
    end
    HeroManager.SelectedWeaponPartnerId = this.curHeroData.partnerId
    this.effDelayTimer = utimer.timeCall(function()
        if levelup then
            levelup.selectedIndex = 1;
            if curWeaponData.level == 20 or curWeaponData.level == 40 or curWeaponData.level == 60 then
                this.skillLevelUpCtrl.selectedIndex = 0
                this.UpIcon()
            else
                this.skillLevelUpCtrl.selectedIndex = 1
            end
        end
        this.LoadUpEff()
    end, this._delayOpenLevelUp, 1);
    --showUI(PanelNames.UIWeaponLevelUp, this.goFunc)
    this:refreshPanel();
    this:onClickLevelUp();
    -- local needStars = decodeJsonStrToTabel(weaponConfig.f_WeaponNeedStar);
    -- if curWeaponData.level>#needStars or needStars[curWeaponData.level+1]>curHeroData.star then
    --     UISysTips.AddMsg(string.format(getLanguage("Sys_WeaponCantRankup"),EnumConst.StarType[needStars[curWeaponData.level+1]/10]));
    --     return;
    -- end

    -- weaponHandler.sendWeaponUpLevelMessage(curHeroData.partnerId,curWeaponData.level);
end

--只允许升到单一材料可升的最高阶段
function UIWeapon.onClickOneKeyAddLv()
    if not canClickUp then
        return
    end
    if curWeaponData.level == -1 then
        return
    end
    if curWeaponData.level >= weaponConfig.f_MaxLevel then
        --已达最大等级
        UISysTips.AddMsg(getLanguage("UIWeapon_MaxLv"))
        return ;
    end
    local lvCost = weaponLvCostConfig[curWeaponData.level + 1];
    local itemNum = logicMgr.ItemManager.getCurrencyCountByModelId(lvCost[1]);
    if itemNum < lvCost[2] then
        --升1级的材料都不够
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),getLanguage(G.dataTable["t_item"][tostring(lvCost[1])].f_ItemName)))
        return ;
    end
    HeroManager.SelectedWeaponPartnerId = this.curHeroData.partnerId
    this:refreshPanel()
    if this.currentWeaponLv > this.maxWeaponLv
            or this.weaponNeedStarArr[this.currentWeaponLv] > this.currentPartnerStar then
        UISysTips.AddMsg(string.format(getLanguage("Sys_WeaponCantRankup"), EnumConst.StarType[this.weaponNeedStarArr[this.currentWeaponLv + 1] / 10]))
        return
    end
    showUI(PanelNames.UIWeaponLevelUpConfirm, HeroManager.SelectedWeaponPartnerId)
end

function this.dispatchWeaponLevelUp()
    --this:refreshPanel()
end

function this:onClickLevelUp()
    --升级
    if this.currentWeaponLv > this.maxWeaponLv
            or this.weaponNeedStarArr[this.currentWeaponLv] > this.currentPartnerStar then
        UISysTips.AddMsg(string.format(getLanguage("Sys_WeaponCantRankup"), EnumConst.StarType[this.weaponNeedStarArr[this.currentWeaponLv + 1] / 10]))
        return
    end
    this.mask.visible = true
    weaponHandler.sendWeaponUpLevelMessage(HeroManager.SelectedWeaponPartnerId, this.currentWeaponLv - 1)
end

function UIWeapon.CloseLevelPanel()
    levelup.selectedIndex = 0;
    this.mask.visible = false
    if this.effFront ~= nil then
        destroyImmediate(this.effFront);
        this.effFront = nil
    end
end

function UIWeapon.onClickAttribute()
    closeUI(PanelNames.UIWeapon);
    showUI(PanelNames.UICharactorInfoHero, logicMgr.HeroManager.getHeroDatabyPartnerId(curHeroData.partnerId, true), 1);
end

function UIWeapon.onClickEquip()
    closeUI(PanelNames.UIWeapon);
    showUI(PanelNames.UICharactorInfoHero, logicMgr.HeroManager.getHeroDatabyPartnerId(curHeroData.partnerId, true), 2);
end

function UIWeapon.onClickSkill()
    closeUI(PanelNames.UIWeapon);
    showUI(PanelNames.UICharactorInfoHero, logicMgr.HeroManager.getHeroDatabyPartnerId(curHeroData.partnerId, true), 3);
end
function UIWeapon.onClickBefore()
    local index = 0;
    for i = 1, #allHero do
        if allHero[i]["partnerModelId"] == curHeroData["partnerModelId"] then
            index = i;
            break ;
        end
    end
    index = index - 1;
    if index < 1 then
        index = #allHero;
    end
    curHeroData = allHero[index];
    this.refresh();
end

function UIWeapon.onClickNext()
    local index = 0;
    for i = 1, #allHero do
        if allHero[i]["partnerModelId"] == curHeroData["partnerModelId"] then
            index = i;
            break ;
        end
    end
    index = index + 1;
    if index > #allHero then
        index = 1;
    end
    curHeroData = allHero[index];
    this.refresh();
end

function UIWeapon.onClickClose()
    closeUI(PanelNames.UIWeapon);
end

function this.FragmentWear()
    this.fragmentEffectWrap:SetActive(true)
    Util.PlayAction(this.fragmentEffectWrap, "idle1", false)
    this.fragmentTimer = utimer.timeCall(function()
        utimer.remove(this.fragmentTimer)
        this.fragmentTimer = nil
        this.firstEnter = true
        this.refresh()
    end, 500, 1)
end
function this.FragmentUnwear()
    this.fragmentEffectWrap:SetActive(false)
    this.firstEnter = true
    this.refresh()
end
function this.FragmentSwap()
    this.fragmentEffectWrap:SetActive(true)
    Util.PlayAction(this.fragmentEffectWrap, "idle1", false)
    this.fragmentTimer = utimer.timeCall(function()
        utimer.remove(this.fragmentTimer)
        this.fragmentTimer = nil
        this.firstEnter = true
        this.refresh()
    end, 500, 1)
end

function UIWeapon.OnClickGo()
    showUI(PanelNames.UISource, function()
        if this.goFunc then
            this.goFunc();
        end
    end, this.costId);
end

function UIWeapon.onClickSource()
    --showUI(PanelNames.UISource, function ()
    --    if this.goFunc then
    --        this.goFunc();
    --    end
    --end, this.costId);
    this.showSourceController.selectedIndex = 1;
    this.showSourceList = { this.costId }
    logicMgr.ItemManager.setSourceStart("UIWeapon", true)
    this.effectController.selectedIndex = 0;
    this.updateSource();
end

function UIWeapon.updateSource()
    logicMgr.ItemManager.updateSourceUI(this.sourceUIobj, this.showSourceList, function()
        this.showSourceController.selectedIndex = 0;
    end, function()
        this.showSourceController.selectedIndex = 0;
        if this.goFunc then
            this.goFunc();
        end
    end);
end
--------------------------
function UIWeapon.rendererWeaponAttributeItem(index, obj)
    local attr_txt = obj:GetChild("attrText")
    local num_txt = obj:GetChild("num")
    local upNum_txt = obj:GetChild("upNum")
    num_txt.width = 114
    upNum_txt.width = 114
    if index == 0 then
        attr_txt.text = getLanguage("Sys_HeroLevel")
        num_txt.text = this.currentWeaponLv ~= 0 and this.currentWeaponLv - 1 or 0
        upNum_txt.text =  this.currentWeaponLv
        return
    end
    local _attributeInfo = this.attributeArr[index]
    HelperFunc.SetIcon(obj:GetChild("loader_icon"), "attr" .. _attributeInfo.nextAttributeId, EnumConst.ItemShowType.ICON)
    attr_txt.text = _attributeInfo.attributeName
    num_txt.text = _attributeInfo.currentAttributeStr
    upNum_txt.text = _attributeInfo.nextAttributeStr
    if index > 3 then
        if curWeaponData.level < 20 then
            obj.visible = false
        else
            obj.visible = true
        end
    end
end

function this:refreshPanel()
    local _currentPartnerInfo = HeroManager.getHeroDatabyPartnerId(HeroManager.SelectedWeaponPartnerId, true)
    if not _currentPartnerInfo then
        return
    end
    local _configId = 150000 + tonumber(_currentPartnerInfo.partnerModelId)
    local _weaponConfig = G.dataTable["t_weapon"][tostring(_configId)]
    local _currentWeaponInfo = EquipManager.tabWeapon[tostring(_currentPartnerInfo.partnerId)]
    if _currentWeaponInfo == nil then
        printError("UIWeaponLevelUp currentWeaponInfo is Null, partnerId " .. _currentPartnerInfo.partnerId)
        this:onClickClose()
        return
    end

    this.currentPartnerStar = _currentPartnerInfo.star
    this.currentWeaponLv = _currentWeaponInfo.level + 1
    this.maxWeaponLv = _weaponConfig.f_MaxLevel
    this.weaponNeedStarArr = decodeJsonStrToTabel(_weaponConfig.f_WeaponNeedStar)
    if _currentWeaponInfo.attiredId == 0 then
        local _weaponShowConfig = decodeJsonStrToTabel(_weaponConfig.f_WeaponShow)
        _currentWeaponInfo.attiredId = _weaponShowConfig[1][2]
    end

    local _weaponValue = decodeJsonStrToTabel(_weaponConfig.f_WeaponValue)
    local _currentWeaponAttribute = _weaponValue[this.currentWeaponLv]

    local _currentWeaponEnergyCost = decodeJsonStrToTabel(_weaponConfig.f_WeaponEnergyCost)
    local _levelUpCost = _currentWeaponEnergyCost[this.currentWeaponLv]
    --local _levelUpItemConfig = ItemManager.getItemConstDatabyModelId(_levelUpCost[1])
    --  this.Img_CostIcon.url = EnumConst.AtlasPath.ItemAtlas .. _levelUpItemConfig.icon

    if this.currentWeaponLv <= this.maxWeaponLv then
        --激活下一级
        this.costId = _levelUpCost[1]
        local _myselfItemNumber = ItemManager.getCurrencyCountByModelId(_levelUpCost[1])
        local _costStr = getNumString(_myselfItemNumber)
        local _levelUpState = 0
        if _myselfItemNumber < _levelUpCost[2] then
            --判断材料是否充足
            _costStr = string.TextColor(_costStr, "#FF0000")
            _levelUpState = 1
            -- if not logicMgr.ItemManager.getSourceStart("UIWeapon") then
            --     this.effectController.selectedIndex = 1;
            -- end
        end
        _costStr = _costStr .. "/" .. getNumString(_levelUpCost[2])
        -- this.Txt_CostNumber.text = _costStr
        --this.Controller_LevelUp.selectedIndex = _levelUpState
        --this.Btn_LevelUp.enabled = _touchable
        --this.Btn_LevelUp.touchable = _touchable
        local _levelUpStatus = 1
        if this.currentWeaponLv == 1 then
            _levelUpStatus = 0
        end
        this.LevelUpController.selectedIndex = _levelUpStatus
        this.currentWeaponLevel = _currentWeaponInfo.level

        --属性列表
        local _nextWeaponAttribute = _weaponValue[this.currentWeaponLv+1]
        this.attributeArr = {}
        for _, nextAttribute in ipairs(_nextWeaponAttribute) do
            local _attributeData = {}
            _attributeData.nextAttributeId = nextAttribute[1]
            local _nextAttributeLibrary = G.dataTable["t_attributelibrary"][tostring(_attributeData.nextAttributeId)]
            _attributeData.attributeName = _nextAttributeLibrary.f_AttributeName
            _attributeData.nextAttributeNumber = nextAttribute[2]

            local _attributeNumberStr = ""
            if _nextAttributeLibrary.f_AttributeType == 1 then
                _attributeNumberStr = getNumString(_attributeData.nextAttributeNumber)
            elseif _nextAttributeLibrary.f_AttributeType == 2 then
                _attributeNumberStr = string.format("+%0.1f%%", tostring(_attributeData.nextAttributeNumber / 100))
            end
            _attributeData.nextAttributeStr = _attributeNumberStr
            _attributeData.newStatus = 1

            --当前属性
            if _currentWeaponAttribute == nil then
                _attributeData.currentAttributeStr = string.format("+%0.1f%%", tostring(0 / 100))
            else
                for _, currentAttribute in ipairs(_currentWeaponAttribute) do
                    if _attributeData.nextAttributeId == currentAttribute[1] then
                        _attributeData.currentAttributeNumber = tonumber(currentAttribute[2])
                        _attributeNumberStr = "+0"
                        _attributeData.newStatus = 1;
                        _attributeData.newStatus = 1;
                        if _attributeData.currentAttributeNumber > 0 then
                            _attributeData.newStatus = 0
                            if _nextAttributeLibrary.f_AttributeType == 1 then
                                _attributeNumberStr = getNumString(_attributeData.currentAttributeNumber)
                            elseif _nextAttributeLibrary.f_AttributeType == 2 then
                                _attributeNumberStr = string.format("+%0.1f%%", tostring(_attributeData.currentAttributeNumber / 100))
                            end
                        end
                        _attributeData.currentAttributeStr = _attributeNumberStr
                        break
                    end
                end
            end
            table.insert(this.attributeArr, _attributeData)
        end
        this.List_WeaponAttribute.numItems = #this.attributeArr + 1
        --HelperFunc.ListTranstionPlay(this.List_WeaponAttribute)
    else
        --满级
        attrList.itemRenderer = this.SetData
    end
end

function UIWeapon.refreshShop()
    this.btnShop.visible = false;
    local actState = logicMgr.CostManager.getFastConsumption();
    if actState == 0 or (actState == 1 and logicMgr.CostManager.isFastConsumptionItems(3)) then
        if not this.hasAddRedDots and actState == 0 then
            this.hasAddRedDots = true;
            UIRedDots.addViewListen(PanelResNames.UIWeapon, gameObjectName .. this.btnShop.gameObjectName, this.btnShop, Config.RedDotsType.CostGiftLink);
        end
        this.btnShop.visible = true;
    end
end

function UIWeapon.onClickShop()
    showUI(PanelResNames.UIGiftLink, 3, -1, function()
        this.refresh();
    end);
end

return UIWeapon;
